const App = getApp();
const wxParse = require("../../wxParse/wxParse.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    item: [],
    join: [],
    isLoading: true,
    page: 1,
    no_more: false,

    contentTtext:false,//商品详情

    indicatorDots: true, // 是否显示面板指示点
    autoplay: true, // 是否自动切换
    interval: 3000, // 自动切换时间间隔
    duration: 800, // 滑动动画时长

    currentIndex: 1, // 轮播图指针
    floorstatus: false, // 返回顶部
    showView: true, // 显示商品规格
    // 分享按钮组件
    share: {
      show: false,
      cancelWithMask: true,
      cancelText: '关闭',
      actions: [
      //   {
      //   name: '生成商品海报',
      //   className: 'action-class',
      //   loading: false
      // },
       {
        name: '发送给朋友',
        openType: 'share'
      }],
      // 商品海报
      showPopup: false,
      
    },

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(e) {
    let _this = this;
    this.setData({
      id: e.id ? e.id : 0,
      status: e.status ? e.status :'',
    });
    console.log(e.id);
    //根目录路径
    this.setData({
      app_root: App.root
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //用户详情
    //this.getUserDetail();
    //优惠券详情
    this.getDetail();
  },

  /**
   * 获取当前用户信息
   */
  getUserDetail: function () {
    let _this = this;
    App._get('user.index/detail', {}, function (result) {
      _this.setData({
        user_id: result.data.userInfo['user_id']
      });
    });
  },

  /**
   * 优惠券详情
   */
  getDetail: function (isNextPage, page) {
    let _this = this;
    App._get('recharge/getIndexDetail', {
      id: _this.data.id,
      status: _this.data.status
    }, function (result) {
      console.log(result);
      let data = _this.initCouponsDetailData(result.data.list);
      _this.setData({
        item: data,
      });
      //console.log(data);
      //参与者高度
      _this.setSwiperHeight();
    });
  },

  /**
   * 初始化优惠券详情数据
   */
  initCouponsDetailData: function (data) {
    let _this = this;
    // 富文本转码
    if (data.content &&  data.content.length > 0) {
      wxParse.wxParse('content', 'html', data.content, _this, 0);
    }
    return data;
  },

  // 点击加载更多
  triggerDownLoad: function () {
    // 已经是最后一页
    if (this.data.page >= this.data.last_page) {
      this.setData({
        no_more: true
      });
      return false;
    }
    this.getDetail(true, ++this.data.page);
  },



  /**
   * 设置swiper的高度
   */
  setSwiperHeight: function (isTap) {
    let join_num = this.data.join_num;
    // 获取系统信息(拿到屏幕宽度)
    let systemInfo = wx.getSystemInfoSync(),
      rpx = systemInfo.windowWidth / 750, // 计算rpx
      //tapHeight = isTap ? Math.floor(rpx * 82) : 0, // tap高度
      //peopleHeight = Math.floor(rpx * 65), // people高度
      tang = Math.floor(rpx * 210),
      more = Math.floor(rpx * 100),
      swiperHeight = tang * join_num + more; // swiper高度

    this.setData({
      swiperHeight
    });
  },

  /**
   * 初始化商品详情数据
   */
  initGoodsDetailData: function(data) {
    let _this = this;
    // 富文本转码
    if (data.detail.content.length > 0) {
      wxParse.wxParse('content', 'html', data.detail.content, _this, 0);
    }
    // 商品价格/划线价/库存
    // data.goods_sku_id = data.detail.sku[0].spec_sku_id;
    // data.goods_price = data.detail.sku[0].goods_price;
    // data.line_price = data.detail.sku[0].line_price;
    // data.stock_num = data.detail.sku[0].stock_num;
    // 单规格商品封面图
    data.image_path = data.detail.image[0]['file_path'];
    // 多规格商品封面图
    // if (data.detail.spec_type == 20 && data.detail.sku[0]['image']) {
    //   data.image_path = data.detail.sku[0]['image']['file_path'];
    // }
    // // 初始化商品多规格
    // if (data.detail.spec_type == 20) {
    //   data.specData = _this.initManySpecData(data.specData);
    // }
    return data;
  },

  /**
   * 设置轮播图当前指针 数字
   */
  setCurrent: function(e) {
    this.setData({
      currentIndex: e.detail.current + 1
    });
  },

 
  /**
   * 返回顶部
   */
  goTop: function(t) {
    this.setData({
      scrollTop: 0
    });
  },

  /**
   * 显示/隐藏 返回顶部按钮
   */
  scroll: function(e) {
    this.setData({
      floorstatus: e.detail.scrollTop > 200
    })
  },


  /**
   * 加入购物车and立即购买
   */
  submit: function(e) {
    let _this = this,
      submitType = e.currentTarget.dataset.type;
    if (submitType === 'buyNow') {
      // 立即购买
      wx.navigateTo({
        url: '../flow/checkout?' + App.urlEncode({
          order_type: 'buyNow',
          goods_id: _this.data.goods_id,
          goods_num: _this.data.goods_num,
          goods_sku_id: _this.data.goods_sku_id
        }),
        success() {
          // 关闭弹窗
          _this.onToggleTrade();
        }
      });
    } else if (submitType === 'addCart') {
      // 加入购物车
      App._post_form('cart/add', {
        goods_id: _this.data.goods_id,
        goods_num: _this.data.goods_num,
        goods_sku_id: _this.data.goods_sku_id,
      }, function(result) {
        App.showSuccess(result.msg);
        _this.setData(result.data);
      });
    }
  },

  /**
   * 浏览商品图片
   */
  previewImages: function(e) {
    let index = e.currentTarget.dataset.index,
      imageUrls = [];
    this.data.detail.image.forEach(function(item) {
      imageUrls.push(item.file_path);
    });
    wx.previewImage({
      current: imageUrls[index],
      urls: imageUrls
    })
  },

  /**
   * 预览Sku规格图片
   */
  previewSkuImage: function(e) {
    wx.previewImage({
      current: this.data.image_path,
      urls: [this.data.image_path]
    })
  },

  /**
   * 跳转到评论
   */
  navigateToComment: function() {
    wx.navigateTo({
      url: './comment/comment?goods_id=' + this.data.goods_id
    })
  },

  /**
   * 分享当前页面
   */
  onShareAppMessage: function() {
    // 构建页面参数
    let params = App.urlEncode({
      'goods_id': this.data.goods_id,
      'referee_id': App.getUserId()
    });
    return {
      title: this.data.detail.goods_name,
      desc: "",
      path: "/pages/goods/index?" + params
    };
  },

  /**
   * 显示分享选项
   */
  openActionsheet(e) {
    // 记录formId
    App.saveFormId(e.detail.formId);
    this.setData({
      'share.show': true
    });
  },

  /**
   * 关闭分享选项
   */
  closeActionSheet() {
    this.setData({
      'share.show': false
    });
  },

  /**
   * 点击分享选项
   */
  clickAction(e) {
    // if (e.detail.index === 0) {
    //   // 显示商品海报
    //   this.showPoster();
    // }
    this.closeActionSheet();
  },

  /**
   * 切换商品海报
   */
  togglePopup() {
    this.setData({
      'share.showPopup': !this.data.share.showPopup
    });
  },

  /**
   * 显示商品海报图
   */
  showPoster: function() {
    let _this = this;
    wx.showLoading({
      title: '加载中',
    });
    App._get('goods/poster', {
      goods_id: _this.data.goods_id
    }, function(result) {
      _this.setData(result.data, function() {
        _this.togglePopup();
      });
    }, null, function() {
      wx.hideLoading();
    });
  },

  /**
   * 保存海报图片
   */
  savePoster: function(e) {
    let _this = this;
    // 记录formId
    App.saveFormId(e.detail.formId);
    wx.showLoading({
      title: '加载中',
    });
    // 下载海报图片
    wx.downloadFile({
      url: _this.data.qrcode,
      success: function(res) {
        wx.hideLoading();
        // 图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function(data) {
            wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000
            });
            // 关闭商品海报
            _this.togglePopup();
          },
          fail: function(err) {
            if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
              wx.showToast({
                title: "请允许访问相册后重试",
                icon: "none",
                duration: 1000
              });
              setTimeout(function() {
                wx.openSetting();
              }, 1000);
            }
          },
          complete(res) {
            console.log('complete');
            // wx.hideLoading();
          }
        })
      }
    })
  },

  /**
   * 确认购买弹窗
   */
  onToggleTrade(e) {
    if (typeof e === 'object') {
      // 记录formId
      e.detail.hasOwnProperty('formId') && App.saveFormId(e.detail.formId);
    }
    this.setData({
      showBottomPopup: !this.data.showBottomPopup
    });
  },
  // 点击详情页 展开/搜索
  clickcontent:function(){
    
    if (this.data.contentTtext == false){
      this.setData({
        contentTtext: true
      });
    }else{
      this.setData({
        contentTtext: false
      });
    }
  },
  //取消报名加入
  uncancel:function(e){
    let _this = this;
    let doing_user_id = e.currentTarget.dataset.doing_user_id;
    let key = e.currentTarget.dataset.key;
    wx.showModal({
      title: '提示',
      content: '您确定要取消报名吗？',
      success(res) {
        if (res.confirm) {
          App._get('doing/uncancel', {
            doing_user_id: doing_user_id,
            doing_id: _this.data.doing_id
          }, function (result) {
              console.log(result);

            // if (result.code == 1) {
            //   wx.navigateBack()
            // }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  //进入商店
  goToShop: function (e) {
    let shop_id = e.target.dataset.shop_id;
    //console.log(shop_id);
    wx.navigateTo({
      url: '/pages/shop/detail?shop_id=' + shop_id
    })
  },

  goBack:function(){
    wx.navigateBack();
  },
  //充值
  recharge:function(e){
    let _this = this;
    let id = e.currentTarget.dataset.id;
    let key = e.currentTarget.dataset.key;
    //console.log(key);

    wx.showModal({
      title: '提示',
      content: '您确定要充值吗？',
      success(res) {
        if (res.confirm) {
          App._get('recharge/addMoney', {
            id: id,
            key:key
          }, function (result) {
            console.log(result)
            //未登录
            if (result.data.code == 2) {
              App.showIsLogin(result.msg);
            }
            //console.log(result);
            callback(result);
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })


    // 订单创建成功后回调--微信支付
    let callback = function (result) {
      if (result.code === -10) {
        App.showError(result.msg, function () {
          // 跳转到未付款订单
          // wx.redirectTo({
          //   url: '/pages/doing/user/index?type=' + type,
          // });
        });
        return false;
      }
      // 发起微信支付
      wx.requestPayment({
        timeStamp: result.data.payment.timeStamp,
        nonceStr: result.data.payment.nonceStr,
        package: 'prepay_id=' + result.data.payment.prepay_id,
        signType: 'MD5',
        paySign: result.data.payment.paySign,
        success: function (res) {
          App.showSuccess('充值成功');
        },
        fail: function () {
          // App.showError('订单未支付', function () {
          //   // 跳转到未付款订单
          //   wx.redirectTo({
          //     url: '/pages/doing/user/index?type=' + type,
          //   });
          // });
        },
      });
    };
  },

})